package com.hmtech.ayp.contoller;

import cn.hutool.core.codec.Base64Decoder;
import com.hmtech.ayp.common.resp.R;
import com.hmtech.ayp.common.s3.domain.S3UploadResult;
import com.hmtech.ayp.common.s3.service.IS3Service;
import com.hmtech.ayp.domain.dto.EditImageDTO;
import com.hmtech.ayp.domain.entity.Style;
import com.hmtech.ayp.openai.OpenAIClient;
import com.hmtech.ayp.service.IStyleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/image")
@Slf4j
public class ImageEditController {
    @Autowired
    private OpenAIClient openAIClient;
    @Autowired
    private IStyleService styleService;
    @Autowired
    private IS3Service s3Service;

    @PostMapping("/edits")
    public R<S3UploadResult> edits(@ModelAttribute EditImageDTO request) throws Exception {
        Style style = styleService.getOneById(request.getStyleId());
        if (null == style) {
            throw new RuntimeException("Style not found");
        }
        long start = System.currentTimeMillis();
        String base64 = openAIClient.transfer(style.getPrompt(), request.getImage());
        byte[] bytes = Base64Decoder.decode(base64);
        S3UploadResult s3UploadResult = s3Service.upload(request.getImage().getOriginalFilename(), bytes);
        log.info("edit image cost {} ms", System.currentTimeMillis() - start);
        return R.ok(s3UploadResult);
    }
}
